/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/11/2
 */

import { request, config, token } from 'utils';
import moment from 'moment';

const { api } = config;
const { authorization } = api;

export async function getTokenFromLocal () {
  return token.loadFromDisk() && token.valueOf();
}

export async function doLogin (params) {
  const resp = await request({
    url: authorization.login,
    method: 'post',
    data: params,
  });
  const { results: { Token, TokenTime }, success } = resp;
  if (success) {
    if (Token) {
      // 写入本地存储
      token.create({
        tokenString: Token,
        expireAt: moment(TokenTime).add(72 * 3600 * 1000),
      });
    }
  }

  return resp;
}

export async function doLogout (params) {

  const resp = await request({
    url: authorization.logout,
    method: 'post',
    data: params,
  });

  if (resp.success) {
    token.clear();
  }

  return resp;
}

export async function checkAuth ({ password }) {
  const res = await request({
    url: authorization.checkAuth,
    method: 'post',
    data: {
      password,
    },
  });

  if (!res.success || res.error > 0) {
    return false;
  }

  return true;
}
